#include "hsr04.h"


/**
 * 函数名：HSR04_Init()
 * 功能：超声波的初始化
 * 引脚：PB5(Trig) | PB4(Echo)
 * 占用的内设资源：TIM6,EXTI_Line4
 */
void HSR04_Init()
{
    GPIO_InitTypeDef  GPIO_InitSture;
	EXTI_InitTypeDef  EXTI_InitSture;
	NVIC_InitTypeDef  NVIC_InitSture;
    TIM_TimeBaseInitTypeDef   TIM_TimeBaseInitSture;
	
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6,ENABLE);
	GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable,ENABLE);
	
    /**************************GPIO结构体的初始化**********************************/
	GPIO_InitSture.GPIO_Mode=GPIO_Mode_Out_PP;   
	GPIO_InitSture.GPIO_Pin=Trig;             
	GPIO_InitSture.GPIO_Speed=GPIO_Speed_10MHz;  
	GPIO_Init(Trig_Port,&GPIO_InitSture);
	
	GPIO_InitSture.GPIO_Mode=GPIO_Mode_IN_FLOATING;    
	GPIO_InitSture.GPIO_Pin=Echo;               
	GPIO_Init(Echo_Port,&GPIO_InitSture);

    /**************************EXTI外部中断结构体的初始化***************************/
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource4);
	EXTI_InitSture.EXTI_Line=EXTI_Line4;
	EXTI_InitSture.EXTI_LineCmd=ENABLE;
	EXTI_InitSture.EXTI_Mode=EXTI_Mode_Interrupt;
	EXTI_InitSture.EXTI_Trigger=EXTI_Trigger_Rising;
	EXTI_Init(&EXTI_InitSture);

    /**************************NVIC中断结构体的初始化*******************************/
	NVIC_InitSture.NVIC_IRQChannel=EXTI4_IRQn;
	NVIC_InitSture.NVIC_IRQChannelCmd=ENABLE;
	NVIC_InitSture.NVIC_IRQChannelPreemptionPriority=2;
	NVIC_InitSture.NVIC_IRQChannelSubPriority=2;
	NVIC_Init(&NVIC_InitSture);
	
    /***********************TimeBase时基结构体的初始化*******************************/
	TIM_TimeBaseInitSture.TIM_CounterMode=TIM_CounterMode_Up;
	TIM_TimeBaseInitSture.TIM_Period=5000;
	TIM_TimeBaseInitSture.TIM_Prescaler=7199;
	TIM_TimeBaseInitSture.TIM_ClockDivision=0;
	TIM_TimeBaseInit(TIM6,&TIM_TimeBaseInitSture);
}

/**
 * 函数名：HSR04_Init()
 * 功能：驱动Trig发送超声波
 * 返回参数：Distance(距离)——全局变量
 */
void HSR04_Trig_Open()
{
    GPIO_SetBits(GPIOB,Trig);
    delay_us(20);
    GPIO_ResetBits(GPIOB,Trig);
}

int Distance;
void EXTI4_IRQHandler()
{
    int Distance_test;
    if(EXTI_GetITStatus(EXTI_Line4) != RESET)
    {
        TIM_SetCounter(TIM6,0);
        TIM_Cmd(TIM6,ENABLE);
        while(GPIO_ReadInputDataBit(GPIOB,Echo)==1);
        
        TIM_Cmd(TIM6,DISABLE);
        Distance_test=TIM_GetCounter(TIM6)*340/200;
        if(Distance_test<450)
        {
            Distance=Distance_test;
            printf("Distance: %d\r\n",Distance);
        }
        else
        {
            printf("The data is wrong!");
        }
    }
    EXTI_ClearITPendingBit(EXTI_Line4);
}
